﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Security.Cryptography;
using Newtonsoft.Json;
using SuperX.Common.Log;
using SuperX.Common.Helper;
using SuperX.Common;
using SuperX.Common.BasicService;
using SuperX.Common.AppConfiguration;

namespace SuperX.Helper.OS
{
    public class LinuxCommand : OSCommand
    {
        public string PrettyName { get; }

        public LinuxCommand()
        {
            Init();
        }

        private void Init()
        {
            Stopwatch sw = Stopwatch.StartNew();

            var readCpuTask = Task.Factory.StartNew(() =>
            { _envContext.CpuId = ReadSingleResult("sudo dmidecode -t 4 | grep ID"); });

            var readMotherBoardTask = Task.Factory.StartNew(() =>
            { _envContext.MotherBoardId = ReadSingleResult("sudo dmidecode -t 2 | grep Serial"); });

            //var readNetworkAdapterMacAddressTask = Task.Factory.StartNew(() =>
            //{ _netAdapterMacAddress = ReadAllResult("ifconfig -a"); });

            var readNetworkAdapterMacAddressTask = Task.Factory.StartNew(() =>
            { _envContext.NetAdapterMacAddress = GetAllNetworkMacAddresses(); });

            var result = Task.WaitAll(new Task[] { readCpuTask, readMotherBoardTask, readNetworkAdapterMacAddressTask }, 5000);
            if (!result)
            {
                Logger.Error("Read Hardware infomation timeout 10s");
            }
            Logger.Trace($"CPU ID: {_envContext.CpuId}");
            Logger.Trace($"MotherBoard ID: {_envContext.MotherBoardId}");
            Logger.Trace($"Mac Address: {string.Join(";", _envContext.NetAdapterMacAddress)}");
            Logger.Trace($"Read Hardware infomation Consume time(ms): {sw.ElapsedMilliseconds}");
        }

        internal static LinuxCommand GetNewLinuxCommand()
        {
            string osField = null;
            if (File.Exists("/etc/redhat-release"))
            {
                var content = File.ReadAllText("/etc/redhat-release");
                osField = content;
            }
            else if (File.Exists("/etc/os-release"))
            {
                var lines = File.ReadAllLines("/etc/os-release");
                //var pattern = "(?<=^NAME=\").*(?=\")";
                //var regexResult = Regex.Match(content, pattern);
                foreach (var line in lines)
                {
                    if (line.StartsWith("NAME=") && line.Length > "NAME=".Length + 2)
                    {
                        osField = line.Substring("NAME=".Length + 1, line.Length - 2 - "NAME=".Length);
                        break;
                    }
                }
            }
            Console.WriteLine("GetNewLinuxCommand " + osField);
            if (!string.IsNullOrWhiteSpace(osField))
            {
                var type = OSCommand.LoadType(osField, typeof(LinuxCommand));
                if (type != null)
                {
                    return Activator.CreateInstance(type) as LinuxCommand;
                }
            }
            Logger.Warn("无法识别该操作系统的类型");
            return new LinuxCommand();
        }

        #region 脚本执行

        public override string ScriptExecute(string content)
        {
            return Bash(content);
        }

        ///执行bash命令
        public static string Bash(string cmd)
        {
            var escapedArgs = cmd.Replace("\"", "\\\"");

            var process = new Process()
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "/bin/bash",
                    Arguments = $"-c \"{escapedArgs}\"",
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                }
            };
            process.Start();
            string result = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
            process.Close();
            process?.Dispose();
            return result;
        }

        #endregion 脚本执行

        #region 路径

        public override string GetIoTDataDir()
        {
            return "/IOTData";
        }

        public override string GetSystemTmpDir()
        {
            string tmpDirName = "IOTTmp";//临时文件夹名字
            var baseDir = GetIoTDataDir();
            return System.IO.Path.Combine(baseDir, tmpDirName);//本地存储的临时路径
        }

        public override string GetProjectDownLoadDir()
        {
            string tmpDirName = "DownLoad";//下载文件位置
            var projectDir = SystemCfgService.GetInstance().SystemCfg.ProjectConfig.ProjectDirPath;
            return System.IO.Path.Combine(projectDir, tmpDirName);
        }

        public override string GetGatewayBaseDir()
        {
            return "/IOTData";
        }

        public override string GetGatewayCurrentDir()
        {
            var currentDir = Path.GetDirectoryName(new Uri(this.GetType().Assembly.CodeBase).AbsolutePath);
            return currentDir;
        }

        public override string GetLogDir()
        {
            return "/IOTData/logs";
        }

        public override string GetGatewayOutputBaseDir()
        {
            return "/IOTData/IoTFiles"; ;
        }

        #endregion 路径

        #region 信息统计

        /// <summary>
        /// 系统统计的上下文
        /// </summary>
        private class EnvContext
        {
            public string CpuId { get; set; }

            public string MotherBoardId { get; set; }

            public List<string> NetAdapterMacAddress { get; set; }

            public string OSDescription { get; set; }

            public DateTime? OSStartTime { get; set; }
        }

        private EnvContext _envContext = new EnvContext();

        public override double GetMemory(string processName)
        {
            int processId = FindProcessByNameInlinux(processName + ".dll");
            if (processId < 0) return double.NaN;
            var process = new List<Process>() { Process.GetProcessById(processId) };
            return process.FirstOrDefault().WorkingSet64 / 1024 / 1024;
        }

        public override string GetOSDescription()
        {
            if (!string.IsNullOrEmpty(_envContext.OSDescription))
            {
                return _envContext.OSDescription;
            }
            //string version = ProcessManager.Bash("lsb_release -a|grep Description")?.Trim();
            // return version?.Substring("Description:".Length).Trim();
            var desc = "Linux";
            if (File.Exists("/etc/os-release"))
            {
                var lines = File.ReadAllLines("/etc/os-release");
                foreach (var line in lines)
                {
                    if (line.StartsWith("PRETTY_NAME=") && line.Length > "PRETTY_NAME=".Length + 2)
                    {
                        desc = line.Substring("PRETTY_NAME=".Length + 1, line.Length - 2 - "PRETTY_NAME=".Length);
                        break;
                    }
                }
            }
            else if (File.Exists("/etc/redhat-release"))
            {
                var content = File.ReadAllText("/etc/redhat-release");
                desc = content;
            }
            _envContext.OSDescription = desc;
            return desc;
        }

        public override DateTime GetGatewayStartTime()
        {
            if (_envContext.OSStartTime != null)
            {
                return _envContext.OSStartTime.Value;
            }
            var timeStr = Bash("uptime -s");
            DateTime.TryParse(timeStr, out var time);
            _envContext.OSStartTime = time;
            return time;
        }

        private string ReadSingleResult(string bashCommand)
        {
            var resultArray = SplitLines(Bash(bashCommand));
            foreach (var item in resultArray)
            {
                var index = item.IndexOf(":");
                if (index < 0) continue;
                var id = item.Substring(index + 1).Replace(" ", string.Empty).Replace(":", string.Empty).Replace("-", string.Empty);
                if (!string.IsNullOrWhiteSpace(id))
                {
                    return id;
                }
            }
            return string.Empty;
        }

        private List<string> GetAllNetworkMacAddresses()
        {
            IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            if (nics == null || nics.Length < 1)
            {
                Console.WriteLine("No network interfaces found.");
                return null;
            }
            var result = new List<string>();
            foreach (NetworkInterface adapter in nics)
            {
                if (adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
                IPInterfaceProperties properties = adapter.GetIPProperties(); //  .GetIPInterfaceProperties();
                PhysicalAddress address = adapter.GetPhysicalAddress();
                byte[] bytes = address.GetAddressBytes();
                var currentMacAddress = string.Empty;
                for (int i = 0; i < bytes.Length; i++)
                {
                    currentMacAddress += bytes[i].ToString("x2");
                }
                result.Add(currentMacAddress);
            }
            return result;
        }

        private string[] SplitLines(string input)
        {
            if (input == null) return null;
            var result = input.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            return result;
        }

        public override string GetCpuID()
        {
            return _envContext.CpuId;
        }

        public override string GetMotherBoardID()
        {
            return _envContext.MotherBoardId;
        }

        public override List<string> GetNetAdapterMacAddress()
        {
            return _envContext.NetAdapterMacAddress;
        }

        private const string SN_PATH = "/proc/sysinfo/sn"; //sn号
        private const string MODEL_PATH = "/proc/sysinfo/model"; //设备型号

        public override List<string> GetHardwareInfo()
        {
            if (File.Exists(SN_PATH) && File.Exists(MODEL_PATH))
            {
                // 查看是否是鼎桥网关
                var snContent = File.ReadAllText(SN_PATH).Trim();
                var modelContent = File.ReadAllText(MODEL_PATH).Trim();
                if (modelContent.StartsWith("eCube-") && snContent.Length > 0)
                {
                    return new List<string>() { snContent };
                }
            }
            return null;
        }

        private bool Is_eCube_Gateway()
        {
            if (File.Exists(MODEL_PATH))
            {
                var modelContent = File.ReadAllText(MODEL_PATH).Trim();
                return modelContent.StartsWith("eCube-");
            }
            return false;
        }

        #endregion 信息统计

        #region 进程管理

        public override void StartBrowser(string uri)
        {
        }

        ///启动进程
        // 例如：/home/chun/桌面/ProcessTest/Console1/bin/Debug/netcoreapp2.2/Console1.dll
        private void StartProcessInLinux(string fileName)
        {
            var startInfo = new ProcessStartInfo()
            {
                FileName = "dotnet",
                Arguments = fileName,
                CreateNoWindow = true,
                UseShellExecute = false
            };
            Process.Start(startInfo);
        }

        ///根据文件名获取进程
        ///例如 /Console1.dll
        private int FindProcessByNameInlinux(string name)
        {
            var bashResult = Bash("ps aux | grep dotnet");
            var array = bashResult.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var pStr in array)
            {
                var ss = pStr.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                if (ss.Last().EndsWith(name))
                {
                    return Convert.ToInt32(ss[1]);
                }
            }
            return -1;
        }

        public override List<Process> GetProcesses(string processName)
        {
            int processId = FindProcessByNameInlinux(processName + ".dll");
            if (processId < 0) return null;
            return new List<Process>() { Process.GetProcessById(processId) };
        }

        public override void StartProcess(string fileFullPathName)
        {
            StartProcessInLinux(fileFullPathName);
        }

        public override void ExitSelfProcess(string processName = null)
        {
            if (processName != null)
            {
                var command = string.Format("systemctl stop {0}", processName);
                Bash(command);
            }
        }

        public void SystemdStop(string serviceName)
        {
            Bash(string.Format("systemctl stop {0}", serviceName));
        }

        public void SystemdStart(string serviceName)
        {
            Bash(string.Format("systemctl start {0}", serviceName));
        }

        public void SystemdRestart(string serviceName)
        {
            Bash(string.Format("systemctl restart {0}", serviceName));
        }

        public override void MonitorHelperStopProcess(string processName, string reason, string serviceName)
        {
            SystemdStop(serviceName);
        }

        public override void MonitorHelperStartProcess(string processName, string reason, string serviceName)
        {
            SystemdStart(serviceName);
        }

        public override void GatewayRestart(string fileFullPathName, string reason, string processName)
        {
            Logger.Info($"（{reason}）运行时停止监听程序");
            SystemdStop(processName);
            //Bash(string.Format("systemctl stop {0}", processName);
            Logger.Info($"（{reason}）运行时启动监听程序");
            //Bash(string.Format("systemctl start {0}", processName);2
            SystemdStart(processName);
        }

        #endregion 进程管理

        public override void CheckOtherUpdate(InvokeMsg msg)
        {
            string commandStr = "command";
            string result = Bash("sudo lsof /var/lib/dpkg/lock");
            if (!string.IsNullOrEmpty(result) && result.ToLower().Contains(commandStr))
            {
                var array = result.Split('\n');      //分行
                for (int i = 0; i < array.Length; i++)
                {
                    if (array[i].ToLower().Contains(commandStr) && i + 1 < array.Length)//当前行包含“Command”，代表为行头，且存在有下一行
                    {
                        string command = array[i + 1].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0];
                        msg.ReturnBody = command;//把正在占用dpkg锁的命令返回给客户端
                        break;
                    }
                }
            }
        }

        #region IP管理

        public override Tuple<bool, bool, List<string>> GetAutoAndDns(string adapterName, IPInterfaceProperties property, string ipv4)
        {
            if (string.IsNullOrEmpty(adapterName))
            {
                return null;
            }

            var str = Bash("nmcli connection show");
            var uuid = GetLinuxUUId(str, adapterName);
            if (string.IsNullOrEmpty(uuid))
            {
                return null;
            }

            var networkInfoStr = Bash($"nmcli connection show {uuid}");
            var rowArray = networkInfoStr.Split('\n');
            var DnsAuto = true;
            var IsDHCP = true;
            var Dns = new List<string>();
            foreach (var item in rowArray)
            {
                if (item.StartsWith("ipv4.ignore-auto-dns"))
                {
                    Logger.Info(item);
                    char[] chs = { ' ' };
                    var colInfo = item.Split(chs, options: StringSplitOptions.RemoveEmptyEntries);//以空格符分割一行
                    if (colInfo.Length >= 2)
                    {
                        DnsAuto = colInfo[1] != "是" || colInfo[1] != "yes";
                    }
                }
                else if (item.StartsWith("ipv4.addresses"))
                {
                    Logger.Info(item);
                    char[] chs = { ' ' };
                    var colInfo = item.Split(chs, options: StringSplitOptions.RemoveEmptyEntries);//以空格符分割一行
                    if (colInfo.Length >= 2)
                    {
                        IsDHCP = colInfo[1] == "--";
                    }
                }
                else if (item.StartsWith("ipv4.dns:"))
                {
                    Logger.Info(item);
                    char[] chs = { ' ' };
                    var colInfo = item.Split(chs, options: StringSplitOptions.RemoveEmptyEntries);//以空格符分割一行
                    if (colInfo.Length >= 2)
                    {
                        if (colInfo[1] != "--")
                        {
                            var colInfoArray = colInfo[1].Split(',');
                            foreach (var dns in colInfoArray)
                            {
                                Dns.Add(dns);
                            }
                        }
                    }
                }
            }
            if (IsDHCP == false)
            {
                DnsAuto = false;//转换成和我们界面的使能一直.
            }
            return new Tuple<bool, bool, List<string>>(IsDHCP, DnsAuto, Dns);
        }

        /// <summary>
        /// climn命令返回后,解析相应网卡的uuid
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetLinuxUUId(string str, string newworkName)
        {
            if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(newworkName))
            {
                return string.Empty;
            }

            var rowArray = str.Split('\n');
            if (rowArray.Length == 1)//返回的结果只有一行说明没有网卡
            {
                Logger.Info("没有可用的网卡!");
                return string.Empty;
            }
            for (int rowNum = 1; rowNum < rowArray.Length; rowNum++)
            {
                if (!rowArray[rowNum].Contains(newworkName))
                {
                    continue;
                }

                char[] chs = { ' ' };
                var colInfo = rowArray[rowNum].Split(chs, options: StringSplitOptions.RemoveEmptyEntries);//以空格符分割一行
                if (colInfo.Length > 3)
                {
                    return colInfo[colInfo.Length - 3];//取倒数第三个
                }
            }
            return string.Empty;
        }

        public override bool SetIPAddress(string ip, string editIp, string submask, string gateway, string[] dns, bool dnsAuto, bool dchpAuto, string mac)
        {
            return SetLinuxIp(ip, new string[] { editIp }, new string[] { submask }, new string[] { gateway }, dns, dnsAuto, dchpAuto);
        }

        private bool SetLinuxIp(string ipIdentify, string[] ip, string[] submask, string[] getway, string[] dns, bool dnsAuto, bool dchpAuto)
        {
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (var adapter in adapters)
            {
                IPInterfaceProperties property = adapter.GetIPProperties();
                foreach (UnicastIPAddressInformation imformation in property.UnicastAddresses)
                {
                    if (imformation.Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        continue;
                    }

                    if (imformation.Address?.ToString() != ipIdentify)
                    {
                        continue;
                    }

                    var str = Bash("nmcli connection show");
                    if (string.IsNullOrEmpty(str))
                    {
                        continue;
                    }

                    var uuId = GetLinuxUUId(str, adapter.Name);
                    if (string.IsNullOrEmpty(uuId))
                    {
                        Logger.Info("uuId获取失败!");
                        return false;
                    }
                    var dnsStr = "";
                    foreach (var item in dns)
                    {
                        dnsStr += $"{item},";
                    }
                    if (!string.IsNullOrEmpty(dnsStr))
                    {
                        if (dnsStr.Length > 2)
                        {
                            dnsStr = dnsStr.Substring(0, dnsStr.Length - 1);
                        }
                    }
                    var subnetMaskInt = ParseSubnetMask(submask[0]);
                    string methodStr;
                    if (!dchpAuto)
                    {
                        if (string.IsNullOrEmpty(getway[0]))
                        {
                            methodStr = $"sudo nmcli connection modify {uuId} ipv4.method manual ipv4.addresses {ip[0]}/{subnetMaskInt} ipv4.dns \"{dnsStr}\"";
                        }
                        else
                        {
                            methodStr = $"sudo nmcli connection modify {uuId} ipv4.method manual ipv4.addresses {ip[0]}/{subnetMaskInt} ipv4.gateway {getway[0]} ipv4.dns \"{dnsStr}\"";
                        }
                        Bash(methodStr);
                        Bash($"sudo nmcli connection modify {uuId} ipv4.ignore-auto-dns true");
                    }
                    else
                    {
                        if (dnsAuto)
                        {
                            methodStr = $"sudo nmcli connection modify {uuId} ipv4.method auto ipv4.dns \"\"";
                            Bash(methodStr);
                            Bash($"sudo nmcli connection modify {uuId} ipv4.ignore-auto-dns false");
                            // ProcessManager.Bash($"sudo nmcli connection up {uuId}");//应用此网卡
                        }
                        else
                        {
                            methodStr = $"sudo nmcli connection modify {uuId} ipv4.method auto ipv4.dns \"{dnsStr}\"";
                            Bash(methodStr);
                            Bash($"sudo nmcli connection modify {uuId} ipv4.ignore-auto-dns true");
                        }
                    }

                    Bash($"sudo nmcli connection up {uuId}");//应用此网卡
                    return true;
                }
            }
            return true;
        }

        private int ParseSubnetMask(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return int.MinValue;
            }

            string[] tokens = str.Split('.');
            string result = "";
            foreach (string token in tokens)
            {
                int tokenNum = int.Parse(token);
                string octet = Convert.ToString(tokenNum, 2);
                while (octet.Length < 8)
                {
                    octet = octet + '0';
                }

                result += octet;
            }
            var subnetInt = result.LastIndexOf('1') + 1;
            return subnetInt;
        }

        private bool EnableLinuxDHCP(string name, bool dnsAuto, string[] dnsArray)
        {
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (var adapter in adapters)
            {
                if (adapter.Name != name)
                {
                    continue;
                }

                var str = Bash("nmcli connection show");
                if (string.IsNullOrEmpty(str))
                {
                    continue;
                }

                var uuId = GetLinuxUUId(str, adapter.Name);
                if (string.IsNullOrEmpty(uuId))
                {
                    Logger.Info("uuId获取失败!");
                    return false;
                }
                var commandStr = $"sudo nmcli connection modify {uuId} ipv4.method auto ipv4.addresses \"\" ipv4.gateway \"\"";
                Bash(commandStr);
                if (dnsAuto)
                {
                    Bash($"sudo nmcli connection modify {uuId} ipv4.method auto ipv4.dns \"\"");
                    Bash($"sudo nmcli connection modify {uuId} ipv4.ignore-auto-dns false");
                }
                else
                {
                    var dnsStr = "";
                    foreach (var item in dnsArray)
                    {
                        dnsStr += $"{item},";
                    }
                    if (!string.IsNullOrEmpty(dnsStr))
                    {
                        if (dnsStr.Length > 2)
                        {
                            dnsStr = dnsStr.Substring(0, dnsStr.Length - 1);
                        }
                    }
                    Bash($"sudo nmcli connection modify {uuId} ipv4.method auto ipv4.dns \"{dnsStr}\"");
                    Bash($"sudo nmcli connection modify {uuId} ipv4.ignore-auto-dns true");
                }
                Bash($"sudo nmcli connection up {uuId}");//应用此网卡
                return true;
            }
            return true;
        }

        public override bool EnableDHCP(string name, string identifyIp, bool dnsAuto, string[] dnsArray)
        {
            return EnableLinuxDHCP(name, dnsAuto, dnsArray);
        }

        #endregion IP管理

        #region NTP(时间同步)

        public const string NTPClientSettingFilePath_linux = @"/etc/systemd/timesyncd.conf";
        public const string NTPServerSettingFilePath_linux = @"/etc/ntp.conf";

        public const string NTPServerSetting_1 = "server 127.127.1.0";
        public const string NTPServerSetting_2 = "fudge 127.127.1.0 stratum 10";

        /// <summary>
        /// 停止NTP的所有服务
        /// </summary>
        private void StopService_Linux()
        {
            //设置开机自启动的启用或者停止会比较耗时
            Bash("sudo systemctl disable systemd-timesyncd.service");//停止客户端开机自启动
            Bash("sudo systemctl disable ntp.service");              //停止服务开机自启动

            var str1 = Bash("sudo systemctl stop systemd-timesyncd.service");//停止客户端服务
            if (!String.IsNullOrEmpty(str1))
            {
                Logger.Info(str1);
            }
            var str2 = Bash("sudo systemctl stop ntp");//停止服务端服务
            if (!String.IsNullOrEmpty(str2))
            {
                Logger.Info(str2);
            }
        }

        /// <summary>
        /// 恢复成最初的设定
        /// </summary>
        private void RecoverOriginalSetting_Linux()
        {
            //1.恢复纯粹客户端时的配置
            string oldNTPClientSetting = GetNTPClientSetting_linux();
            if (!string.IsNullOrEmpty(oldNTPClientSetting) && !oldNTPClientSetting.StartsWith("#NTP"))
            {
                ReplaceText_Linux(NTPClientSettingFilePath_linux, oldNTPClientSetting, $"#NTP=");//存在，则替换
            }

            //2.恢复服务端的初始配置
            if (!File.Exists(NTPServerSettingFilePath_linux)) return;
            string text = "";
            using (StreamReader reader = new StreamReader(NTPServerSettingFilePath_linux, Encoding.UTF8))
            {
                //读一行
                string line = reader.ReadLine();
                while (line != null)
                {
                    //如果这一行里面有相应字符串，就不加入到text中（server 127.127.1.0）
                    if (!line.ToLower().StartsWith("server") && !line.Contains(NTPServerSetting_2))
                    {
                        text += line + Environment.NewLine;
                    }
                    //一行一行读
                    line = reader.ReadLine();
                }
            }
            //定义一个写入流，将值写入到里面去
            using (StreamWriter writer = new StreamWriter(NTPServerSettingFilePath_linux))
            {
                writer.Write(text);
            }
        }

        private void SetNTPClient_Linux(NTPContext ntpContext)
        {
            if (ntpContext.EnableNTPServer || !ntpContext.EnableNTPClient) return;

            string oldNTPClientSetting = GetNTPClientSetting_linux();
            string newStr = $"NTP={ntpContext.NTPServerIP}";
            if (string.IsNullOrEmpty(oldNTPClientSetting))
            {
                AddLineText_Linux(NTPClientSettingFilePath_linux, new List<string>() { $"{newStr}" });//如果不存在，则加上
            }
            else
            {
                ReplaceText_Linux(NTPClientSettingFilePath_linux, oldNTPClientSetting, newStr);//存在，则替换
            }

            Bash("sudo systemctl enable systemd-timesyncd.service");             //客户端服务开机自启动
            var result = Bash("sudo systemctl restart systemd-timesyncd.service");//重启服务
            if (!string.IsNullOrEmpty(result))
            {
                Logger.Info(result);
            }
        }

        private void SetNTPServer_Linux(NTPContext ntpContext)
        {
            if (!ntpContext.EnableNTPServer) return;

            if (ntpContext.EnableNTPClient)
            {
                List<string> IPs = new List<string>();

                #region 添加界面输入的IP

                if (ntpContext.EnableNTPClient && !string.IsNullOrEmpty(ntpContext.NTPServerIP))
                {
                    var strs = ntpContext.NTPServerIP.Split(' ');//以空格作为分隔
                    if (strs != null && strs.Length > 0)
                    {
                        IPs.Add($"server {strs[0]} prefer");//输入的第一个IP作为第一优选
                        if (strs.Length > 1)
                        {
                            for (int i = 1; i < strs.Length; i++)
                            {
                                if (string.IsNullOrEmpty(strs[i])) continue;
                                IPs.Add($"server {strs[i]}");
                            }
                        }
                    }
                }

                #endregion 添加界面输入的IP

                IPs.Add(NTPServerSetting_1);
                IPs.Add(NTPServerSetting_2);

                AddLineText_Linux(NTPServerSettingFilePath_linux, IPs);//在配置文件加入参数
            }

            Bash("sudo systemctl enable ntp.service");      //服务开机自启动
            var result = Bash("sudo systemctl restart ntp");//重启服务
            if (!string.IsNullOrEmpty(result))
            {
                Logger.Info(result);
            }
        }

        /// <summary>
        /// 检查是否作为NTP服务端
        /// </summary>
        /// <returns></returns>
        private bool CheckEnableNTPServer_Linux(NTPContext ntpContext)
        {
            bool result = false;
            try
            {
                //1.获取NTP服务状态
                var str = Bash("service ntp status");
                if (!str.ToLower().Contains("running")) return result = false;//服务未在运行
                result = true;                                                //代表服务在运行

                //2.读取配置，看是否作为客户端在连接其他服务器
                using (StreamReader sr = new StreamReader(NTPServerSettingFilePath_linux, Encoding.UTF8)) //path为文件路径
                {
                    String line;
                    while ((line = sr.ReadLine()) != null)//按行读取 line为每行的数据,读出的行数据不包含换行符
                    {
                        if (line.StartsWith("server") && line != NTPServerSetting_1 && line != NTPServerSetting_2)
                        {
                            var ip = GetIPFromStr_Linux(line);
                            if (string.IsNullOrEmpty(ip)) continue;
                            if (string.IsNullOrEmpty(ntpContext.NTPServerIP))
                            {
                                ntpContext.NTPServerIP = ip;
                            }
                            else
                            {
                                ntpContext.NTPServerIP = $"{ntpContext.NTPServerIP} {ip}";//拼接IP，以空格“ ”分隔
                            }
                        }
                    }
                }
                if (!String.IsNullOrEmpty(ntpContext.NTPServerIP))
                {
                    ntpContext.EnableNTPClient = true;//启用作为客户端连接其他IP
                }
            }
            catch (Exception ex)
            {
                Logger.Exception(ex);
            }
            return result;
        }

        /// <summary>
        /// 检查是否作为NTP客户端
        /// </summary>
        /// <returns></returns>
        private bool CheckEnableNTPClient_Linux(NTPContext ntpContext)
        {
            bool result = false;
            try
            {
                //1.获取客户端服务状态
                var str = Bash("service systemd-timesyncd status");
                if (str.ToLower().Contains("running")) result = true;//服务在运行

                //2.读取配置，看是否作为客户端在连接其他服务器。如：NTP=
                string oldNTPClientSetting = GetNTPClientSetting_linux();
                if (!string.IsNullOrEmpty(oldNTPClientSetting) && oldNTPClientSetting.StartsWith("NTP"))
                {
                    string[] arrs = oldNTPClientSetting.Split('=');
                    if (arrs.Length > 1 && !string.IsNullOrEmpty(arrs[1]))
                    {
                        ntpContext.NTPServerIP = arrs[1].Replace("\n", "");//时间同步服务器的IP
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Exception(ex);
            }
            return result;
        }

        /// <summary>
        /// 获取有NTP客户端配置信息的那一行
        /// </summary>
        /// <returns></returns>
        private string GetNTPClientSetting_linux()
        {
            if (!File.Exists(NTPClientSettingFilePath_linux)) return "";
            using (StreamReader sr = new StreamReader(NTPClientSettingFilePath_linux, Encoding.UTF8)) //path为文件路径
            {
                String line;
                while ((line = sr.ReadLine()) != null)//按行读取 line为每行的数据,读出的行数据不包含换行符
                {
                    if (line.StartsWith("#NTP") || line.StartsWith("NTP"))
                    {
                        return line;
                    }
                }
            }
            return null;
        }

        private void ReplaceText_Linux(string filePath, string oldStr, string newStr)
        {
            string newText = string.Empty;
            //读取文本　
            using (StreamReader sr = new StreamReader(filePath, Encoding.UTF8))
            {
                newText = sr.ReadToEnd();
                newText = newText.Replace(oldStr, newStr);
            }
            //更改保存文本
            using (StreamWriter sw = new StreamWriter(filePath, false))
            {
                sw.WriteLine(newText);
            }
        }

        /// <summary>
        /// 按行添加文本
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="lines"></param>
        private void AddLineText_Linux(string filePath, List<string> lines)
        {
            if (lines == null || lines.Count <= 0) return;
            string newText = string.Empty;
            //读取文本　
            using (StreamReader sr = new StreamReader(filePath, Encoding.UTF8))
            {
                newText = sr.ReadToEnd();
                foreach (var item in lines)
                {
                    if (string.IsNullOrEmpty(item)) continue;
                    if (!newText.EndsWith(Environment.NewLine))
                    {
                        newText = newText + $"{Environment.NewLine}{item}";//把信息加上去，并且加上换行符
                    }
                    else
                    {
                        newText = newText + $"{item}";//把信息加上去，并且加上换行符
                    }
                }
            }
            //更改保存文本
            using (StreamWriter sw = new StreamWriter(filePath, false))
            {
                sw.WriteLine(newText);
            }
        }

        /// <summary>
        /// 从字符串中提取IP
        /// 如：server 127.127.1.0 prefer
        /// </summary>
        /// <returns></returns>
        private string GetIPFromStr_Linux(string str)
        {
            if (string.IsNullOrEmpty(str)) return null;
            var strs = str.Split(' ');//以空格分隔
            if (strs.Length >= 2)
            {
                return strs[1];//返回IP
            }
            return null;
        }

        public override void GetNTP(NTPContext ntpContext)
        {
            //linux下【ntp.service】（作为服务器、客户端）和【systemd-timesyncd.service】（纯粹作为客户端）只能启动其中一个，一个启动了，另一个会停止
            ntpContext.EnableNTPServer = CheckEnableNTPServer_Linux(ntpContext);
            ntpContext.EnableNTPClient = false;
            if (!ntpContext.EnableNTPServer)
            {
                ntpContext.EnableNTPClient = CheckEnableNTPClient_Linux(ntpContext);
            }
        }

        public override void SetNTP(NTPContext ntpContext)
        {
            //只要勾选了启动作为服务器，就只配置服务器对应的文件。
            StopService_Linux();     //停止所有服务
            RecoverOriginalSetting_Linux();//还原最初的配置
            if (ntpContext.EnableNTPServer)
            {
                SetNTPServer_Linux(ntpContext);
            }
            else
            {
                SetNTPClient_Linux(ntpContext);
            }
        }

        #endregion NTP(时间同步)

        #region 更新程序

        public const string UpdateSoftwareTmpDirName = "UpdateSoftwareTmp";//放置更新文件的临时文件夹名

        public const string BatchFileName_Linux = "UpdateSoftware.sh";     //Linux脚本处理文件文件名

        /// <summary>
        /// 开始更新
        /// </summary>
        public override void StartUpdate(string updateSoftwareTmpDir, string subDir)
        {
            try
            {
                var updateSoftwareInfo = new UpdateSoftwareInfo
                {
                    UpdateSoftwareTmpDir = updateSoftwareTmpDir,
                    SubDir = subDir
                };
                GenerateUpdateBat_Linux(updateSoftwareInfo);
                ExecuteBatFile_Linux();
            }
            catch (Exception ex)
            {
                Logger.Exception(ex);
            }
        }

        public override void StartUpdate(string updateSoftwareTmpDir)
        {
            string currentRunningDir = System.IO.Path.GetDirectoryName(new Uri(this.GetType().Assembly.CodeBase).AbsolutePath);//程序运行文件所在的文件夹
            List<string> batchContents = new List<string>();
            batchContents.Add("#!/bin/bash");
            batchContents.Add("echo \"OK\"");
            batchContents.Add("systemctl stop IoTServiceCore.service");       //结束运行时
            batchContents.Add("systemctl stop ListenerServiceCore.service");      //结束监听程序
            batchContents.Add($"rsync -I -av --exclude-from={currentRunningDir}/Script/ExcludeBysh {updateSoftwareTmpDir}/* {currentRunningDir}");      //结束监听程序
            batchContents.Add("systemctl start IoTServiceCore.service");       //结束运行时
            batchContents.Add("systemctl start ListenerServiceCore.service");      //结束监听程序
            batchContents.Add($"rm -r \"{updateSoftwareTmpDir}\"");      //删除临时放置更新文件的文件夹
            batchContents.Add($"rm \"/IOTData/Script/UpdateSoftware.sh\"");      //删除更新后的脚本文件
            batchContents.Add("sync;sync;sync");               //写缓存，防止因立即重启导致文件信息丢失
            WriteTxtToFile(batchContents, Path.Combine(GetSystemTmpDir(), BatchFileName_Linux));
            ExecuteBatFile_Linux();
        }

        #region Linux

        protected virtual List<string> GenerateReInstallScript(string fullName)
        {
            var list = new List<string>
            {
                "dpkg -r IoTRun",
                "dpkg -i \"" + fullName + "\""
            };
            return list;
        }

        /// <summary>
        /// 生成linux下的脚本处理文件
        /// </summary>
        private void GenerateUpdateBat_Linux(UpdateSoftwareInfo updateSoftwareInfo)
        {
            List<string> batchContents = new List<string>();
            string batFilePath = System.IO.Path.Combine(updateSoftwareInfo.SubDir, BatchFileName_Linux);

            #region 生成脚本处理里面文件的内容

            //batchContents.Add("sudo systemctl stop IoTRunner.service");       //结束运行时
            //batchContents.Add("sudo systemctl stop IoTMonitor.service");      //结束监听程序
            //if (CheckExistInstaller())                            //存在安装文件，则先卸载，再安装
            //{
            //    batchContents.Add("sudo dpkg -r IoTRun");
            //    batchContents.Add("sudo dpkg -i " + GetInstallerPath_Linux());
            //}
            //else                                                  //不存在安装文件，则只是文件或者dll的更新
            //{
            //    string desDir = Path.GetDirectoryName(new Uri(GetType().Assembly.CodeBase).AbsolutePath);//程序运行文件所在的文件夹

            //    if (_updateSoftwareInfo != null && _updateSoftwareInfo.FileNameAndRelativePaths?.Count > 0)
            //    {
            //        foreach (var item in _updateSoftwareInfo.FileNameAndRelativePaths)
            //        {
            //            string sourceFilePath = Path.Combine(_dir, item.Key); //拼接源路径+文件名
            //            string desPath = Path.Combine(desDir, item.Value);//拼接目标文件夹

            //            batchContents.Add("sudo cp -f " + sourceFilePath + " " + desPath);
            //        }
            //    }
            //    batchContents.Add("sudo systemctl start IoTRunner");       //开启运行时
            //    batchContents.Add("sudo systemctl start IoTMonitor");      //开启监听程序
            //}

            // batchContents.Add("sudo rm -r " + _dir);                       //删除临时放置更新文件的文件夹

            #endregion 生成脚本处理里面文件的内容

            #region 生成脚本处理里面文件的内容

            batchContents.Add("#!/bin/bash");
            batchContents.Add("echo \"OK\"");
            batchContents.Add("systemctl stop IoTRunner.service");       //结束运行时
            batchContents.Add("systemctl stop IoTMonitor.service");      //结束监听程序
            if (CheckExistInstaller(updateSoftwareInfo))                            //存在安装文件，则先卸载，再安装
            {
                //batchContents.Add("dpkg -r IoTRun");
                //batchContents.Add("dpkg -i \"" + GetInstallerPath_Linux(updateSoftwareInfo) + "\"");
                batchContents.AddRange(GenerateReInstallScript(GetInstallerPath_Linux(updateSoftwareInfo)));
            }
            else                                                  //不存在安装文件，则只是文件或者dll的更新
            {
                string currentRunningDir = System.IO.Path.GetDirectoryName(new Uri(this.GetType().Assembly.CodeBase).AbsolutePath);//程序运行文件所在的文件夹
                //获取更新的软件信息
                GetUpdateSoftwareInfo(currentRunningDir, updateSoftwareInfo);
                if (updateSoftwareInfo == null)
                {
                    Logger.Warn(nameof(updateSoftwareInfo) + " is null,return");
                    return;
                }

                if (updateSoftwareInfo != null && updateSoftwareInfo.FileNameAndRelativePaths?.Count > 0)
                {
                    foreach (var item in updateSoftwareInfo.FileNameAndRelativePaths)
                    {
                        string sourceFilePath = System.IO.Path.Combine(updateSoftwareInfo.SubDir, item.Key); //拼接源路径+文件名
                        string desPath = System.IO.Path.Combine(currentRunningDir, item.Value);//拼接目标文件夹

                        batchContents.Add("cp -f \"" + sourceFilePath + "\" \"" + desPath + "\"");
                    }
                }
                batchContents.Add("systemctl start IoTRunner.service");       //开启运行时
                batchContents.Add("systemctl start IoTMonitor.service");      //开启监听程序
            }

            batchContents.Add("rm -r \"" + updateSoftwareInfo.SubDir + "\"");      //删除临时放置更新文件的文件夹
            batchContents.Add("sync;sync;sync");               //写缓存，防止因立即重启导致文件信息丢失

            #endregion 生成脚本处理里面文件的内容

            //写到批处理文件
            WriteTxtToFile(batchContents, batFilePath, updateSoftwareInfo);
        }

        /// <summary>
        /// 执行脚本文件
        /// </summary>
        private void ExecuteBatFile_Linux()
        {
            Logger.Info("开始执行更新脚本");

            string currentRunningDir = System.IO.Path.GetDirectoryName(new Uri(this.GetType().Assembly.CodeBase).AbsolutePath);//程序运行文件所在的文件夹
            var updateServiceName = "IoTRunUpdate.service";
            var IoTUpdateScriptFile = System.IO.Path.Combine(currentRunningDir, "Script", updateServiceName);
            var updateServiceFile = System.IO.Path.Combine("/lib/systemd/system", updateServiceName);
            try
            {
                if (File.Exists(IoTUpdateScriptFile))
                {
                    File.Copy(IoTUpdateScriptFile, updateServiceFile, true);
                }
                else
                {
                    Logger.Warn(string.Format("当前程序不存在文件{0},无法执行更新脚本", IoTUpdateScriptFile));
                    return;
                }
            }
            catch (Exception ex)
            {
                Logger.Info(ex.ToString());
                return;
            }
            var cmd = $"systemctl start {updateServiceName}";
            Logger.Info("执行脚本：" + cmd);
            string result = Bash(cmd);//执行脚本
            Logger.Info("执行脚本完成：" + result);
        }

        /// <summary>
        /// 获取安装包的全路径
        /// </summary>
        /// <returns></returns>
        private string GetInstallerPath_Linux(UpdateSoftwareInfo updateSoftwareInfo)
        {
            string[] files = Directory.GetFiles(updateSoftwareInfo.SubDir);//得到文件
            foreach (string file in files)//循环文件
            {
                string exname = file.Substring(file.LastIndexOf(".") + 1);//得到后缀名
                if (exname.ToLower() == PackageSuffix)
                {
                    return file;
                }
            }
            return null;
        }

        #endregion Linux

        public virtual string PackageSuffix { get; } = "deb";

        /// <summary>
        /// 检查是否存在安装文件
        /// </summary>
        private bool CheckExistInstaller(UpdateSoftwareInfo updateSoftwareInfo)
        {
            string[] files = Directory.GetFiles(updateSoftwareInfo.SubDir);//得到文件
            foreach (string file in files)            //循环文件
            {
                string exname = file.Substring(file.LastIndexOf(".") + 1);//得到后缀名

                if (exname.ToLower() == PackageSuffix)
                {
                    return true;//Linux下安装包
                }
            }
            return false;
        }

        /// <summary>
        /// 获取需要更新的软件信息
        /// </summary>
        private void GetUpdateSoftwareInfo(string currentRunningDir, UpdateSoftwareInfo updateSoftwareInfo)
        {
            string filePath = System.IO.Path.Combine(updateSoftwareInfo.SubDir, "UpdateSoftwareInfo.cfg"); //配置文件
            if (File.Exists(filePath))
            {
                var newInfo = JsonHelper.JsonDeserializeFromFile(filePath, typeof(UpdateSoftwareInfo), Encoding.UTF8) as UpdateSoftwareInfo;
                updateSoftwareInfo.FileNameAndRelativePaths = newInfo.FileNameAndRelativePaths;
            }
            else
            {
                //没有配置文件，则查询以前的dll等文件是放在哪个目录下的
                //以前放哪里，更新的仍然放在对应的地方，如果没有，则默认加在运行的根目录
                //updateSoftwareInfo = new UpdateSoftwareInfo();
                updateSoftwareInfo.FileNameAndRelativePaths = new Dictionary<string, string>();
                GetRunFileInfos(currentRunningDir, currentRunningDir);//先获取原有dll等放置的相对路径

                //遍历放置有更新文件的临时文件夹，获取对应文件信息
                DirectoryInfo Dir = new DirectoryInfo(updateSoftwareInfo.SubDir);
                foreach (FileInfo f in Dir.GetFiles())                             //查找文件
                {
                    if (_runfilesInfos.ContainsKey(f.Name))
                    {
                        updateSoftwareInfo.FileNameAndRelativePaths.Add(f.Name, _runfilesInfos[f.Name]);
                    }
                    else
                    {
                        updateSoftwareInfo.FileNameAndRelativePaths.Add(f.Name, string.Empty);
                    }
                }
            }
        }

        /// <summary>
        /// 写信息到文本
        /// </summary>
        /// <param name="contents">要写的内容</param>
        /// <param name="batFilePath">文件名字路径</param>
        private void WriteTxtToFile(List<string> contents, string batFilePath)
        {
            Logger.Info("批处理文件路径：" + batFilePath);
            if (contents == null || contents.Count <= 0) return;
            FileStream fs = new FileStream(batFilePath, FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);

            foreach (var item in contents)
            {
                sw.WriteLine(item);//生成批处理里面文件的内容
            }

            sw.Flush();
            sw.Close();
            fs.Close();
            fs.Dispose();
            if (File.Exists(batFilePath))
            {
                //Linux下脚本文件要考到指定目录，交由系统服务来调用执行
                var scriptPath = Path.Combine(GetIoTDataDir(), "Script", Path.GetFileName(batFilePath));
                if (!Directory.Exists(Path.GetDirectoryName(scriptPath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(scriptPath));
                }
                File.Copy(batFilePath, scriptPath, true);
                if (File.Exists(batFilePath))
                    File.Delete(batFilePath);
            }
            else
            {
                Logger.Warn($"未能生成批处理文件");
            }
        }

        /// <summary>
        /// 写信息到文本
        /// </summary>
        /// <param name="contents">要写的内容</param>
        /// <param name="batFilePath">文件名字路径</param>
        private void WriteTxtToFile(List<string> contents, string batFilePath, UpdateSoftwareInfo updateSoftwareInfo)
        {
            Logger.Info("批处理文件路径：" + batFilePath);
            if (contents == null || contents.Count <= 0) return;
            FileStream fs = new FileStream(batFilePath, FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);

            foreach (var item in contents)
            {
                sw.WriteLine(item);//生成批处理里面文件的内容
            }

            sw.Flush();
            sw.Close();
            fs.Close();
            fs.Dispose();
            if (File.Exists(batFilePath))
            {
                //Linux下脚本文件要考到指定目录，交由系统服务来调用执行
                File.Copy(batFilePath, Path.Combine(updateSoftwareInfo.UpdateSoftwareTmpDir, Path.GetFileName(batFilePath)), true);
            }
            else
            {
                Logger.Warn($"未能生成批处理文件");
            }
        }

        /// <summary>
        /// 程序运行目录下的文件信息
        /// Key：文件名，Value：相对于运行目录的相对路径。
        /// 用于更新dll等之类时，进行比对。
        /// </summary>
        private Dictionary<string, string> _runfilesInfos = new Dictionary<string, string>();

        /// <summary>
        /// 递归获取程序运行文件夹下的文件信息和子文件夹信息
        /// </summary>
        /// <param name="searchDirPath">要搜索的文件夹路径</param>
        /// <param name="runDirPath">运行目录的路径</param>
        private void GetRunFileInfos(string searchDirPath, string runDirPath)
        {
            if (string.IsNullOrEmpty(searchDirPath)) return;
            if (string.IsNullOrEmpty(runDirPath)) return;
            searchDirPath = searchDirPath.Replace(@"\", "/");                //替换为统一的路径符号
            runDirPath = runDirPath.Replace(@"\", "/");

            searchDirPath = searchDirPath.Replace("//", "/");                 //替换为单“/”，便于下面截取字符串获取准确长度
            runDirPath = runDirPath.Replace("//", "/");

            //在指定目录及子目录下查找文件,在list中列出子目录及文件
            DirectoryInfo Dir = new DirectoryInfo(searchDirPath);

            //获取当前目录的文件信息
            foreach (FileInfo f in Dir.GetFiles())                             //查找文件
            {
                string relativeDir = string.Empty;
                if (searchDirPath != runDirPath)
                {
                    relativeDir = searchDirPath.Substring(runDirPath.Length + 1);//当前搜索的目录与运行的目录不相等，则要截取出当前搜索目录相对于运行目录的相对路径
                }
                if (!_runfilesInfos.ContainsKey(f.Name))
                {
                    _runfilesInfos.Add(f.Name, relativeDir);                   //加到文件信息字典中
                }
            }
            //查找子目录，递归
            DirectoryInfo[] DirSub = Dir.GetDirectories();
            if (DirSub?.Length > 0)
            {
                foreach (DirectoryInfo d in DirSub)
                {
                    GetRunFileInfos(d.FullName, runDirPath);
                }
            }
        }

        #endregion 更新程序

        public override string FormatDirectorySeparatorChar(string content)
        {
            return content.Replace(@"\", "/");
        }

        #region 共享文件夹

        /// <summary>
        /// 创建挂载路径
        /// </summary>
        /// <param name="dirPath">挂载路径</param>
        public override void CreateMountDir(string dirPath)
        {
            ScriptExecute($"sudo mkdir -p {dirPath}");
        }

        /// <summary>
        /// 移除挂载路径
        /// </summary>
        /// <param name="dirPath">挂载的路径</param>
        public override void RemoveMountDir(string dirPath)
        {
            ScriptExecute($"sudo umount {dirPath}");
        }

        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="dirPath">路径</param>
        public override void DeleteDir(string dirPath)
        {
            ScriptExecute($"sudo rm -rf {dirPath}");
        }

        #endregion 共享文件夹

        #region OPCUAServer进程管理

        public override void StartOPCUAServer()
        {
            SystemdStart("IoTOPCUAService");
        }

        public override void StopOPCUAServer()
        {
            SystemdStop("IoTOPCUAService");
        }

        public override bool CheckIfOPCUAServerIsRunning()
        {
            List<Process> processes = IotEnvironment.OSCommand.GetProcesses("IoTOPCUAService");
            if (processes?.Count > 0) return true;
            return false;
        }

        #endregion OPCUAServer进程管理

        public override bool IsSupportIPManager()
        {
            return false;
        }

        public override FunctionState GetSSHServerState()
        {
            return FunctionState.Running;
        }

        public override void RestartSSHServer()
        {
        }

        public override bool UpdateFileExists()
        {
            var CurrentDir = AppDomain.CurrentDomain.BaseDirectory;
            if (!File.Exists(Path.Combine(CurrentDir, "Script", "ExcludeBysh")))
                return false;
            return true;
        }
    }
}